package com.td.module.system.job;

import com.alibaba.fastjson.JSONObject;
import com.td.framework.common.util.date.DateUtils;
import com.td.framework.quartz.core.handler.JobHandler;
import com.td.framework.tenant.core.job.TenantJob;
import com.td.module.system.controller.admin.video.vo.video.VideoUpdateReqVO;
import com.td.module.system.dal.dataobject.video.VideoDO;
import com.td.module.system.service.video.VideoService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

import static com.td.framework.common.util.http.HttpUtils.HttpPost;

/**
 * 获取萤石accessToken的定时任务
 *
 * @author Wangxx
 */
@Component
@TenantJob
public class UpdateYSAccessTokenJob implements JobHandler {
    @Resource
    private VideoService videoService;

    @Override
    public String execute(String param) throws Exception {
        VideoDO videoDO = videoService.getVideo(Long.valueOf(param));
        String url = "https://open.ys7.com/api/lapp/token/get";
        String body = "appKey="+videoDO.getAppKey()+"&appSecret="+videoDO.getAppSecret();
        String res = HttpPost(url, body);

        JSONObject outJson = JSONObject.parseObject(res);
        JSONObject map = outJson.getJSONObject("data");
        VideoUpdateReqVO videoUpdateReqVO = new VideoUpdateReqVO();
        videoUpdateReqVO.setId(Long.valueOf(param))
                .setAppKey(videoDO.getAppKey())
                .setAppSecret(videoDO.getAppSecret())
                .setAccessToken(map.getString("accessToken"))
                .setExpireTime(DateUtils.of(new Date(map.getLong("expireTime"))));
        videoService.updateVideo(videoUpdateReqVO);
        return String.format("萤石账号accessToken更新时间：%S", DateUtils.of(new Date()));
    }
}
